import type { HoldItem } from '@/indexDB/initHold'
import { ref, watch } from 'vue'
import { assetsDB } from '@/indexDB/index'
import { getLastWeekRange } from '@/utils/time'
import { categoryList } from '@/indexDB/initCategory'
import { platformList } from '@/indexDB/initPlatform'
import { strategyList } from '@/indexDB/initStrategy'

export const useHold = (pageSize?: number) => {
  const form = ref<{
    dateList: [start: string, end: string]
    platformId: string | number
    strategyId: string | number
    categoryId: string | number
  }>({
    dateList: getLastWeekRange(),
    platformId: '',
    strategyId: '',
    categoryId: ''
  })

  const pageInfo = ref({
    pageNum: 1,
    pageSize: pageSize ?? 200,
    total: 0
  })

  const holdList = ref<HoldItem[]>([])

  const queryHoldList = async () => {

    const { platformId, strategyId, categoryId } = form.value
    let query = assetsDB.holdList.where('id').above(0)

    if (strategyId) {
      query = query.and((hold) => hold.strategyId === strategyId)
    }

    if (platformId) {
      query = query.and((hold) => hold.platformId === platformId)
    }

    if (categoryId) {
      query = query.and((hold) => hold.categoryId === categoryId)
    }
    const { pageNum, pageSize } = pageInfo.value
    pageInfo.value.total = await query.count()
    holdList.value = await query
      .offset((pageNum - 1) * pageSize)
      .limit(pageSize)
      .reverse()
      .sortBy('holdValue')
      .then(arr => {
        return arr.map(each => {
          const { strategyId, platformId, categoryId } = each
          const category = categoryList.value.find(item => item.id === categoryId)
          const platForm = platformList.value.find(item => item.id === platformId)
          const strategy = strategyList.value.find(item => item.id === strategyId)

          return {
            ...each,
            categoryName: category?.name,
            platFormName: platForm?.name,
            strategyName: strategy?.name
          }
        })
      })
  }
  watch(form.value, queryHoldList)
  watch(pageInfo.value, queryHoldList)

  queryHoldList()
  return {
    form,
    pageInfo,
    holdList,
    queryHoldList
  }
}